import Vue from 'vue'
import Router from 'vue-router'
import Login from '../components/Login'
import Home from '../components/Home'
import Welcome from '../components/Welcome'
import Users from '../components/user/Users'

Vue.use(Router)

const router = new Router({
  routes: [
    { path: '/', redirect: '/login' },
    { path: '/login', component: Login },
    {
      path: '/home',
      component: Home,
      redirect: '/welcome',
      children: [
        {
          path: '/welcome',
          component: Welcome
        },
        {
          path: '/users',
          component: Users
        }
      ]
    }

  ]
})

router.beforeEach((to, from, next) => {
  // to 去哪，from来自哪， next是否通行
  // 1.如果是访问/login 直接放行
  if (to.path === '/login') return next()
  // 2.如果token为空，跳转到 /login
  const tokenStr = window.sessionStorage.getItem('token')
  if (!tokenStr) return next('/login')
  // 3.有token，访问非 /login ，放行
  next()
})

export default router
